<template>
  <div class="login-conatiner">
    <change-lang></change-lang>
    <div class="logo-container">
      <div class="logo-pic"></div>
      <span class="logo-title">移动端开发平台</span>
    </div>
    <!-- 表单登录 -->
    <fm-form class="form-container">
      <fm-field
        class="field-username"
        clearable
        v-model="username"
        name="用户名"
        placeholder="请输入用户名"
        :rules="userRules"
        @focus="checkedField = 'user'"
        @blur="checkedField = null"
        :class="checkedField == 'user' ? 'field-active' : ''"
      >
        <template #prefix-icon>
          <svg-icon
            v-if="checkedField == 'user'"
            icon-class="user-checked"
            class="news-img"
          />
          <svg-icon v-else icon-class="user" class="news-img" />
        </template>
      </fm-field>
      <fm-field
        class="field-pwd"
        clearable
        v-model="password"
        :type="passwordType"
        name="密码"
        placeholder="请输入密码"
        :rules="pwdRules"
        @click-suffix-icon="viewPassword"
        @focus="checkedField = 'pwd'"
        @blur="checkedField = null"
        :class="checkedField == 'pwd' ? 'field-active' : ''"
      >
        <template #prefix-icon>
          <svg-icon
            v-if="checkedField == 'pwd'"
            icon-class="pwd-checked"
            class="news-img"
          />
          <svg-icon v-else icon-class="pwd" class="news-img" />
        </template>
        <template #suffix-icon v-if="showIcon">
          <fm-image
            v-if="passwordType == 'password'"
            class="suffix-icon"
            width="20"
            height="20"
            :src="require('@/assets/img/login/no-visible.png')"
          />
          <fm-image
            v-else
            class="suffix-icon"
            width="20"
            height="20"
            :src="require('@/assets/img/login/visible.png')"
          />
          <!-- <i class="fm-icon fm-icon-eye-o suffix-icon" v-if="passwordType == 'text'"></i>
          <i class="fm-icon fm-icon-closed-eye suffix-icon" v-else></i> -->
        </template>
      </fm-field>
      <div class="sub-menu">
        <fm-checkbox v-model="rememberMe" shape="square">{{
          $t('login.RememberPassword')
        }}</fm-checkbox>
        <!-- <span @click="forgetPassword">{{ $t('login.forgetPassword') }}</span> -->
      </div>
      <div class="login-btn-container">
        <fm-button
          class="login-btn"
          @click="onSubmit"
          block
          type="primary"
          native-type="submit"
          >{{ $t('login.login') }}</fm-button
        >
      </div>
    </fm-form>
  </div>
</template>
<script>
import {
  Button,
  NavBar,
  Form,
  Field,
  Image,
  Icon,
  Checkbox,
  Toast,
} from 'fawkes-mobile-lib'
import { SM4Encrypt } from '@/utils/encryption/sm4'
import { GRANT_TYPE } from '@/config/enums'
import { mapGetters } from 'vuex'
import { SET_TEMP_USER, IS_LOGIN } from '@/store/Mutation/mutationTypes'
import { USER_LOGIN } from '@/store/Action/actionTypes'
import { loadLanguageAsync } from '@/utils/locale' //引入获取系统语言的方法
import { eventBackButton, exitApp } from '@/utils/app'
import changeLang from './changeLang.vue'

export default {
  name: 'login',
  components: {
    changeLang,
    [Button.name]: Button,
    [NavBar.name]: NavBar,
    [Form.name]: Form,
    [Field.name]: Field,
    [Image.name]: Image,
    [Icon.name]: Icon,
    [Checkbox.name]: Checkbox,
  },
  data() {
    return {
      username: '',
      password: '',
      errorParams: {},
      rememberMe: false,
      showIcon: true,
      passwordType: 'password',
      checkedField: null,
      userRules: [
        {
          required: true,
          message: '用户名不能为空',
          trigger: 'onBlur',
        },
      ],
      pwdRules: [
        {
          required: true,
          message: '密码不能为空',
          trigger: 'onBlur',
        },
      ],
    }
  },
  computed: {
    ...mapGetters(['tempUser']),
  },
  watch: {
    username(newUsername) {
      // 清空用户名时密码也清空
      if (!newUsername) {
        this.password = ''
        this.showIcon = true
      }
    },
    password(newPassword) {
      // 清空密码时显示查看密码按钮
      if (!newPassword) {
        this.showIcon = true
      }
    },
  },
  mounted() {
    this.rememberMe = this.$storage.get('rememberMe') === 'true'
    if (this.rememberMe) {
      this.username = this.$storage.get('username')
      this.password = this.$storage.get('password')
      this.showIcon = false
      this.passwordType = 'password'

      //指纹登录 回填账号密码后直接登录
      if (this.$storage.get('enableFinger') == 'true') {
        Fingerprint.show(
          {
            clientId: 'fawkes', //Android: Used for encryption. iOS: used for dialogue if no `localizedReason` is given.
            clientSecret: 'fawkes_secret', //Necessary for Android encrpytion of keys. Use random secret key.
            title: '指纹登录验证',
            disableBackup: true,
            cancelButtonTitle: '取消',
          },
          () => {
            this.onSubmit()
          },
          (err) => {}
        )
      }
    } else {
      this.username = this.tempUser?.username
      this.password = this.tempUser?.password
    }
    // 移除返回上一级路由事件，设置退出应用
    document.removeEventListener('backbutton', this.$back, false)
    document.addEventListener('backbutton', eventBackButton, false)
  },
  beforeDestroy() {
    this.$store.commit(SET_TEMP_USER, {
      password: this.password,
      username: this.username,
    })
    // 恢复默认的返回上一级路由响应事件
    document.removeEventListener('backbutton', eventBackButton, false)
    document.removeEventListener('backbutton', exitApp, false)
    document.addEventListener('backbutton', this.$back, false)
  },
  methods: {
    viewPassword() {
      if (this.passwordType == 'password') {
        this.passwordType = 'text'
      } else {
        this.passwordType = 'password'
      }
    },
    @monitor('click', '用户登录')
    onSubmit() {
      if (!this.username) {
        return Toast('用户名不能为空')
      }
      if (!this.password) {
        return Toast('密码不能为空')
      }
      const loginData = this.getLoginForm()

      if (loginData.password && loginData.username) {
        this.$loading.show({ title: '' })
        this.$store
          .dispatch(USER_LOGIN, loginData)
          .then(() => {
            this.$store.commit(IS_LOGIN, true)
            this.$router.push('/home')
            if (!this.$storage.get('langList')) {
              let key = this.$storage.get('i18nLocale')
              let locale = this.$storage.get('i18nLocaleKey')
              loadLanguageAsync(key, locale, this)
            }
            this.updataStorage()
          })
          .finally(() => {
            this.$loading.hide()
          })
      }
    },
    getLoginForm() {
      const form = {}
      form.grant_type = GRANT_TYPE.PASSWORD
      form.username = this.username
      // if (this.showIcon) {
      form.password = SM4Encrypt(this.password)
      // } else {
      //   form.password = this.password
      // }
      return form
    },
    // 登录成功时更新缓存
    updataStorage() {
      this.$storage.set('username', this.username)
      this.$storage.set('rememberMe', this.rememberMe)
      if (this.rememberMe) {
        this.$storage.set('password', this.password)
      } else {
        this.$storage.remove('password')
      }
      // 记录错误次数
      this.errorParams[this.username] = 0
      this.$storage.set('errorParams', JSON.stringify(this.errorParams))
    },
    goToSignUp() {
      this.$router.push('/signup')
    },
    // 忘记密码
    forgetPassword() {
      this.$router.push('/forget')
    },
  },
}
</script>
<style lang="less" scoped>
/deep/.fm-field__error-message {
  position: absolute;
  top: 80px;
}
/deep/.fm-cell {
  overflow: visible;
}
.suffix-icon {
  margin-left: 10px;
}
/deep/.fm-field__prefix-icon {
  display: flex;
  justify-content: center;
  align-items: center;
}
/deep/.fm-field__suffix-icon {
  display: flex;
  justify-content: center;
  align-items: center;
}
.fm-icon-closed-eye:before {
  width: 36px;
  height: auto;
}
.fm-icon-eye-o:before {
  width: 36px;
  height: auto;
}
.news-img {
  width: 40px;
  height: 40px;
  margin-right: 24px;
}
.fm-field {
  border-radius: 0;
}
.login-conatiner {
  height: 100%;
}
.logo-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding-top: 164px;
  .logo-pic {
    width: 120px;
    height: 120px;
    background-image: url('../../assets/img/login/new-logo.png');
    background-repeat: no-repeat;
    background-size: 100%;
  }
  .logo-title {
    font-weight: bold;
    color: #191919;
    font-size: 40px;
    margin-top: 32px;
  }
}
.tip {
  margin-bottom: 44px;
  font-size: 36px;
  font-weight: 600;
}
.form-container {
  margin-top: 88px;
  padding: 0 80px;
  .sub-menu {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #999;
    font-size: 28px;
    /deep/.fm-checkbox__label {
      color: #999;
    }
  }
}
/deep/.fm-checkbox__icon {
  background-color: #f5f5f5;
}
/deep/.fm-icon {
  border: none;
}
.field-username,
.field-pwd {
  border-bottom: 2px #e3e3e3 solid;
  padding-left: 24px;
  // background-color: #f5f5f5;
  border: 1px solid #ccc;
  // height: 75px;
  margin-bottom: 52px;
  border-radius: 12px;
}
.field-active {
  border: 1px solid #4545d1;
  background-color: #fff;
  /deep/.fm-field__control {
    color: #4545d1 !important;
  }
}

.footer-container {
  padding-top: 260px;
  display: flex;
  justify-content: center;
  .logo-footer {
    width: 134px;
    height: 20px;
  }
}

.login-btn-container {
  margin: 0 auto;
  padding-top: 72px;
  height: 88px;
  .login-btn {
    width: 100%;
    height: 100%;
    font-size: 32px;
    border-radius: 12px;
  }
}
.fm-field--error ::placeholder {
  color: #999999;
}
/deep/ .fm-field--error .fm-field__control,
.fm-field--error .fm-field__control::placeholder {
  color: #999999;
}
.fm-field ::placeholder {
  color: #999999;
}
/deep/.fm-button--primary {
  background-color: #4545d1;
  border: 0.02667rem solid #4545d1;
}
/deep/.fm-checkbox__icon--checked .fm-icon {
  background-color: #4545d1;
}
</style>
